package cn.yerly.sakura.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.yerly.sakura.core.entity.ArcNotFoundException;
import cn.yerly.sakura.core.util.ApplicationUtils;
import cn.yerly.sakura.dao.model.Product;
import cn.yerly.sakura.dao.repository.ProductRepository;
import cn.yerly.sakura.service.ProductService;

/**
 * ProductServiceImpl : 商品业务接口实现
 */
@Service
public class ProductServiceImpl implements ProductService {

	private final Logger logger = LoggerFactory
			.getLogger(ProductServiceImpl.class);

	@Autowired
	ProductRepository productRepository;

	@Override
	public Product addModel(Product product) {

		// 生成id
		Long id = ApplicationUtils.ID_GENERATOR.incrementAndGet();
		product.setId(id);
		return productRepository.save(product);
	}

	@Override
	public Product getModelById(Long id) {

		Product product = productRepository.findOne(id);
		if (product == null) {
			throw new ArcNotFoundException("指定产品不存在");
		}
		return product;
	}

	@Override
	public Product modifyModelById(Product product) {
		Product findOne = productRepository.findOne(product.getId());
		if (product == null) {
			throw new ArcNotFoundException("id为[" + product.getId() + "]的商品不存在");
		}
		findOne.setName(product.getName());
		findOne.setDescription(product.getDescription());

		return productRepository.save(findOne);
	}

	@Override
	public void removeModelById(Long id) {
		if (!productRepository.exists(id)) {
			throw new ArcNotFoundException("id为[" + id + "]的商品不存在");
		}
		productRepository.delete(id);

	}

	@Override
	public Iterable<Product> getModels() {
		int a = 0;
		if (a == 0) {
			throw new RuntimeException("啦啦咬掉");
		}
		return productRepository.findAll();
	}

	@Override
	public List<Product> starProduct(Long id) {

		return null;
	}

	@Override
	public List<Product> unStarProduct(Long id) {
		return null;
	}
}
